#coding=utf-8
#!/usr/bin/python





#     cd /d D:\python26 
#     python.exe D:\py\demo\updb.py

#       python.exe  .\dev_test\db_sqlite.py
   

"""


sqlite

pysqlite-2.6.0.win32-py2.6.exe

处理类
不关心 线程
"""

import os, sys, string
try:
    import sqlite3  as sqlite #载入 文件数据库

except Exception, e:
    print e
    print __file__
    sys.exit()
    
#help(sqlite.connect)
class db_cls():
    def __init__(self): 
        "构建"
        pass
    """
    def __del__(self):
        "析构"
        if (self.init_state['state']  != 0): #未初始化
            pass
        #if self.con:
        #self.con.close()
    """
    def do_init(self,arg_db_file= os.path.dirname(__file__) +os.sep+ 'sql.db'):
        "初始化"
        ret_val = {'error':'not init','state':0}#成功0 失败!=0
        try:
            self.con = sqlite.connect(arg_db_file,isolation_level=None,timeout=120.0)
            #self.con = sqlite.connect(':memory:',isolation_level=None)#内存数据库
            ret_val['error']=''
        except Exception, e:
            ret_val['error']=e
            ret_val['state']=1
            print ret_val['error']
        self.init_state = ret_val #初始化 结果
        return ret_val
    #文件 数据库 
    def test(self,threadname, x):
        u" 不考虑线程执行 "
        self.do_init()
        self.do_sql(u" insert into demo (name)values ('"+ str(threadname) + str(x) +"') ")

        print threadname, x
           

    def do_sql(self,sql,sql_arg=''):
        u"执行 sql"
        #未初始化  
        if (self.init_state['state']  != 0): 
            return self.init_state
        cursor = self.con.cursor()
        state = cursor.execute(sql)
        #居然 插入要提交
        self.con.commit()
        cursor.close ()
        return state

    def get_insert_id(self):
        "插入的id"
        if (self.init_state['state']  != 0):
            return self.init_state
        sql = ' SELECT LAST_INSERT_ID() AS id '
        row = self.get_one(sql)
        return row['id']
        
        
    def get_one(self,sql):
        "一条"
        if (self.init_state['state']  != 0): #未初始化
            return self.init_state
        cursor = self.con.cursor()
        #print sql
        state = cursor.execute (sql)
        #if state:
        #    print 'sql error'
        #row = cursor.fetchone()
        
        #高级
        records = cursor.fetchone()
        if records is None:
            print 'sql error'
            return {}
            
        field = [i[0] for i in cursor.description]
        records2 = dict(zip(field,records))
        return records2
    def get_all(self,sql):
        "所有"
        if (self.init_state['state']  != 0): #未初始化
            return self.init_state
        cursor = self.con.cursor()
        cursor.execute (sql)
        #row = cursor.fetchall()
        
        #高级
        records = cursor.fetchall()
        #return records
        self.rowcount = cursor.rowcount
        field = [i[0] for i in cursor.description]
        records2 = [dict(zip(field,i)) for i in records]

        return records2

    
if __name__ == '__main__':
    db = db_cls()
    #db.test(1,2)
    
    #db.do_init('china.worldscrap.com','root','woshiug')

    """
    db.do_sql('use sms_v2test ');
    db.do_sql(' set names utf8 ');

    """
    db.do_init()
    #db.do_sql(u" insert into demo (name)values ('x我x1') ")
    print db.get_all('select t.tbl_name from sqlite_master t where type="table"; ')

    #print db.get_one('select * from demo; ')['name']
    print __file__ ,':the end'

    sys.exit()


    
